<template>
	<el-container class="layout-container">
		<transition
			name="el-fade-in-linear"
			@after-enter="toggleMenuAndResetTagDiv"
			@after-leave="toggleMenuAndResetTagDiv"
		>
			<el-aside v-if="showLeftBar">
				<el-menu
					:default-openeds="['1']"
					background-color="#545c64"
					active-text-color="white"
					text-color="white"
				>
					<router-link to="/">
						<el-menu-item index="0" @click="autoCloseBar">
							<el-icon><HomeFilled /></el-icon>
							<span>首页</span>
						</el-menu-item>
					</router-link>

					<router-link to="/statistics">
						<el-menu-item index="0" @click="autoCloseBar">
							<el-icon><Histogram /></el-icon>
							<span>统计</span>
						</el-menu-item>
					</router-link>

					<router-link to="/settings">
						<el-menu-item index="0" @click="autoCloseBar">
							<el-icon><Setting /></el-icon>
							<span>设置</span>
						</el-menu-item>
					</router-link>
				</el-menu>
			</el-aside>
		</transition>

		<el-container>
			<el-header>
				<div class="toggle-leftbar" @click="toggleMenu">
					<el-icon style="margin-right: 8px; margin-top: 1px;">
						<Expand v-if="showLeftBar" style="transform: rotateY(180deg);" />
						<Expand v-else />
					</el-icon>
				</div>
				<transition name="el-fade-in-linear">
					<div
						class="header-title"
						v-if="width >= 468 || (!showLeftBar && width < 468)"
					>
						{{ title }}
					</div>
				</transition>
			</el-header>

			<el-main :class="{ 'leftbar-open': showLeftBar }">
				<router-view />
			</el-main>
			<el-footer>
				<p class="footer-tip">
					KANA CARD by
					<a href="https://gitee.com/shawroger/kanacard" targrt="_blank">Roger</a> &copy;
					2022
				</p>
			</el-footer>
		</el-container>
	</el-container>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElContainer, ElMain, ElFooter, ElMessage } from "element-plus";
import {
	HomeFilled,
	Expand,
	Setting,
	Histogram,
} from "@element-plus/icons-vue";

import { KANA_INDEX_RANGE, useStore } from "./store/app";
import { useWindow } from "./utils/useWindow";
import { initKanaData } from "./utils/kanadata";
import { setTagDivHeight } from "./utils/common";
import { initStorage } from "./store/initStorage";

const { width } = useWindow();
const { title, setKana, setKanaAllowIndex } = useStore();
const showLeftBar = ref(width.value > 768);

function toggleMenu() {
	showLeftBar.value = !showLeftBar.value;
}

function autoCloseBar() {
	if (width.value <= 768) {
		showLeftBar.value = false;
	}
}

function toggleMenuAndResetTagDiv(_: HTMLElement, done?: () => void) {
	setTagDivHeight();
	if (typeof done === "function") {
		done();
	}
}

function injectKanaData() {
	const data = initKanaData();

	if (typeof data === "string") {
		return ElMessage.error(data);
	}

	setKana(data);

	const kanaIndexRange = initStorage(
		KANA_INDEX_RANGE,
		data.filter((e) => e.isValid()).map((e) => e.index)
	);

	setKanaAllowIndex(kanaIndexRange);
}

injectKanaData();
</script>
